import CodeTable from '@/services/data-factory/index';
import services from '@/services/demo';
import {
  ActionType,
  FooterToolbar,
  PageContainer,
  ProDescriptions,
  ProDescriptionsItemProps,
  ProTable,
} from '@ant-design/pro-components';
import type { PopconfirmProps } from 'antd';
import { Button, Divider, Drawer, message, Modal, Popconfirm } from 'antd';
import React, { useRef, useState } from 'react';
import CreateForm from './CreateForm';

import StopwatchDetail from './StopwatchDetail';
import UpdateForm, { FormValueType } from './UpdateForm';
// 页面层  调用接口

//分页类型
interface paginationType {
  pageSizeOptions: string[];
  showSizeChanger: boolean;
  total: number;
  current: number;
  pageSize: number;
}

// 气泡确认框
// const confirm: PopconfirmProps['onConfirm'] = (e) => {
//   console.log(e);

//   message.success('操作成功');
// };

const cancel: PopconfirmProps['onCancel'] = (e) => {
  console.log(e);
  message.error('操作取消');
};

// import {  TableDropdown } from '@ant-design/pro-components';queryUserList,
const { modifyUser } = services.UserController;
const {
  getCodeTableListUsingPost,
  batchCodeTableReleaseUsingPut,
  deleteCodeTableUsingDelete,
  getCodeTableDetailUsingGet,
  uploadCodeTableUsingPost,
} = CodeTable.codeTableguanlikongzhiqi;
/**
 * 添加节点
 * @param fields
 */

/**
 * 更新节点
 * @param fields
 */
const handleUpdate = async (fields: FormValueType) => {
  const hide = message.loading('正在配置');
  try {
    await modifyUser(
      {
        userId: fields.id || '',
      },
      {
        name: fields.name || '',
        nickName: fields.nickName || '',
        email: fields.email || '',
      },
    );
    hide();

    message.success('配置成功');
    return true;
  } catch (error) {
    hide();
    message.error('配置失败请重试！');
    return false;
  }
};

const Stopwatch: React.FC<unknown> = () => {
  const [codeTableId, setCodeTableId] = useState<number>();
  const [createModalVisible, handleModalVisible] = useState<boolean>(false);
  const [updateModalVisible, handleUpdateModalVisible] =
    useState<boolean>(false);
  const [stepFormValues, setStepFormValues] = useState({});
  const actionRef = useRef<ActionType>();
  const [row, setRow] = useState<API.UserInfo>();
  const [selectedRowsState, setSelectedRows] = useState<
    dataFactory.QueryCodeTableDTO_[]
  >([]);
  const [data, setData] = useState([]);
  const [pagination, setPagination] = useState<paginationType>({
    pageSizeOptions: ['10', '20', '30'],
    showSizeChanger: true,
    current: 1,
    pageSize: 20,
    total: 0,
  });
  // 获取码表数据列表
  const getCodeTableList = async (params = {}) => {
    const { data, code, msg } = await getCodeTableListUsingPost({
      ...params, // 传递分页、过滤等参数
      pageNumber: pagination.current,
      pageSize: pagination.pageSize,
    });
    console.log(data);
    if (code === 100200) {
      setData(data.records || []); // 更新表格数据
      setPagination((prevPagination) => ({
        ...prevPagination,
        total: data.totalItems, // 更新总条数
      }));
    }
    return {
      data: data || [], // 返回查询到的数据
      code,
      message: msg, // 使用解构出来的 msg
    };
  };
  // 修改状态
  const updataeStatues = async (
    codeTableIdList: number[],
    codeTableStatus: { [key: string]: any } | undefined,
  ) => {
    await batchCodeTableReleaseUsingPut({
      codeTableIdList: codeTableIdList,
      codeTableStatus: codeTableStatus,
    });
    // debugger;
    console.log(codeTableIdList, codeTableStatus);

    message.success('状态修改成功');
    getCodeTableList();
  };
  // 删除码表
  const handleDelete = async (codeTableId: number) => {
    await deleteCodeTableUsingDelete({ codeTableId });
    message.success('删除成功');
    getCodeTableList();
  };
  //// 点击码表编号 详情
  const [detailModalVisible, setDetailModalVisible] = useState(false);

  // 点击码表编号 详情
  const [detailData, setDetailData] = useState<any>(null);
  // 封装接口调用（推荐将接口逻辑单独提取）
  const getCodeTableDetail = async (codeTableId: number) => {
    return getCodeTableDetailUsingGet({ codeTableId });
  };
  // 新增状态保存当前码表编号
  const [codeTableNumber, setCodeTableNumber] = useState<string | undefined>(
    undefined,
  );

  const handleRowClick = (record) => {
    // 设置标题字段
    setCodeTableNumber(record.codeTableNumber || '');
    // 先获取详情数据
    getCodeTableDetail(record.codeTableId).then((res) => {
      if (res.code === 100200) {
        setDetailData(res.data);
      } else {
        message.error('获取详情失败！');
      }
    });

    // 再打开弹窗
    setDetailModalVisible(true);
  };
  // 在组件内部声明 ref 和状态
  const fileInputRef = useRef<HTMLInputElement | null>(null);
  const [selectedFile, setSelectedFile] = useState<File | null>(null);

  // 文件上传逻辑
  const uploadFile = async (file: File) => {
    try {
      const response = await uploadCodeTableUsingPost({}, file);
      if (response?.code === 100200) {
        message.success('导入成功！');
        getCodeTableList();
      } else {
        message.error(`导入失败：${response?.msg || '未知错误'}`);
      }
    } catch (error) {
      message.error(`上传错误：${error?.message || '网络错误'}`);
    }
  };
  const handleFileChange = (e) => {
    const file = e.target.files?.[0];
    if (file) {
      setSelectedFile(file);
      console.log(selectedFile);

      uploadFile(file); //  立即上传文件
    }
  };
  // 导入按钮点击事件
  const handleImport = () => {
    if (!fileInputRef.current) return;
    fileInputRef.current.click();
  };
  const columns: ProDescriptionsItemProps<any>[] = [
    {
      title: '码表编号',
      dataIndex: 'codeTableNumber',
      hideInForm: true,
      hideInSearch: true,
      render: (text, record) => (
        <a
          href="#"
          onClick={(e) => {
            e.preventDefault(); // 阻止默认跳转
            handleRowClick(record); // 触发弹窗
          }}
        >
          {text}
        </a>
      ),
    },

    {
      title: '码表名称',
      dataIndex: 'codeTableName',
      valueType: 'text',
      hideInForm: true,
      formItemProps: {
        // hidden: true,
        rules: [
          {
            required: true,
            message: '中文名称为必填项',
          },
        ],
      },
    },
    {
      title: '码表说明',
      dataIndex: 'codeTableDescription',
      hideInForm: true,
      hideInSearch: true,
    },
    {
      title: '码表状态',
      dataIndex: 'codeTableStatus',
      // hideInTable: true,
      hideInForm: true,
      valueEnum: {
        0: { text: '未发布', status: '0' },
        1: { text: '已发布', status: '1' },
        2: { text: '已停用', status: '2' },
      },
    },
    {
      title: '更新日期',
      dataIndex: 'updateTime',
      hideInSearch: true,
      hideInForm: true,
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => (
        <>
          <Popconfirm
            title="状态确认"
            description="你确定要修改状态吗？"
            onConfirm={() =>
              updataeStatues(
                [record.codeTableId],
                record.codeTableStatus === 0 ? 1 : 0,
              )
            }
            onCancel={cancel}
            okText="确认"
            cancelText="取消"
          >
            {/* {standardStatus ? '发布' : '停用'} */}
            <Button>{record.codeTableStatus === 0 ? '发布' : '停用'}</Button>
          </Popconfirm>
          <Divider type="vertical" />
          <Button
            type="primary"
            onClick={() => {
              setCodeTableId(record.codeTableId);
              handleModalVisible(true);
              setStepFormValues(record); // 记录当前行数据
            }}
            disabled={record.codeTableStatus === 1} // 如果状态为已发布，则禁用编辑按钮
          >
            编辑
          </Button>
          <Divider type="vertical" />
          <Popconfirm
            title="删除确认"
            description="你确定要删除吗？"
            onConfirm={() => {
              handleDelete(record.codeTableId);
            }}
            onCancel={cancel}
            okText="确认"
            cancelText="取消"
          >
            <Button danger>删除</Button>
          </Popconfirm>
        </>
      ),
    },
  ];
  // 检查是否全部选择未发布的数据
  const allSelectedUnpublished = selectedRowsState.every(
    (row) => row.codeTableStatus === 0,
  );
  // 检查是否全部选择已发布的数据
  const allSelectedPublished = selectedRowsState.every(
    (row) => row.codeTableStatus === 1,
  );

  return (
    <PageContainer
      header={{
        title: '码表标准',
      }}
    >
      <input
        ref={fileInputRef}
        type="file"
        onChange={handleFileChange}
        style={{ display: 'none' }}
      />
      <ProTable<API.UserInfo>
        headerTitle="查询表格"
        actionRef={actionRef}
        rowKey="codeTableId"
        search={{
          labelWidth: 70,
        }}
        toolBarRender={() => [
          <Button
            key="1"
            type="primary"
            onClick={() => {
              handleModalVisible(true); // 打开新增模态框
              setStepFormValues({}); // 清空初始值
            }}
          >
            新建码表
          </Button>,
          <Button
            key="2"
            type="primary"
            onClick={() => {
              handleImport();
            }}
          >
            标准导入
          </Button>,
        ]}
        request={getCodeTableList}
        columns={columns}
        pagination={{
          ...pagination,
          onChange: (page, pageSize) => {
            setPagination({
              ...pagination,
              current: page,
              pageSize: pageSize || pagination.pageSize,
            });
          },
        }}
        dataSource={data}
        rowSelection={{
          onChange: (_, selectedRows) => setSelectedRows(selectedRows),
        }}
      />
      {selectedRowsState?.length > 0 && (
        <FooterToolbar
          extra={
            <div>
              已选择{' '}
              <a style={{ fontWeight: 600 }}>{selectedRowsState.length}</a>{' '}
              项&nbsp;&nbsp;
            </div>
          }
        >
          <Button
            type="primary"
            onClick={async () => {
              await updataeStatues(
                selectedRowsState.map((row) => row.codeTableId),
                1,
              );
              setSelectedRows([]);
              actionRef.current?.reloadAndRest?.();
            }}
            disabled={!allSelectedUnpublished} // 禁用条件：没有选择数据或选择的不是未发布的数据
          >
            批量发布
          </Button>
          <Button
            type="primary"
            onClick={async () => {
              await updataeStatues(
                selectedRowsState.map((row) => row.codeTableId),
                2,
              );
              setSelectedRows([]);
              actionRef.current?.reloadAndRest?.();
            }}
            disabled={!allSelectedPublished} // 禁用条件：没有选择数据或选择的不是已发布的数据
          >
            批量停用
          </Button>
        </FooterToolbar>
      )}
      <CreateForm
        onCancel={() => {
          handleModalVisible(false);
          setCodeTableId(undefined); // 关键修复：重置 codeTableId
        }}
        modalVisible={createModalVisible}
        onSuccess={async () => {
          // 新增成功回调
          handleModalVisible(false);
          getCodeTableList();
          setCodeTableId(undefined); // 成功提交后也需重置
          // stepFormValues.codeTableId = '';
          // setCodeTableId(0);
        }}
        getCodeTableList={getCodeTableList}
        initialValues={stepFormValues} // 传递 stepFormValues 作为 initialValues
        codeTableId={codeTableId} // 传递 codeTableId
      ></CreateForm>
      {stepFormValues && Object.keys(stepFormValues).length ? (
        <UpdateForm
          onSubmit={async (value) => {
            const success = await handleUpdate(value);
            if (success) {
              handleUpdateModalVisible(false);
              setStepFormValues({});
              if (actionRef.current) {
                actionRef.current.reload();
              }
            }
          }}
          onCancel={() => {
            handleUpdateModalVisible(false);
            setStepFormValues({});
          }}
          updateModalVisible={updateModalVisible}
          values={stepFormValues}
        />
      ) : null}
      <Drawer
        width={600}
        open={!!row}
        onClose={() => {
          setRow(undefined);
        }}
        closable={false}
      >
        {row?.name && (
          <ProDescriptions<API.UserInfo>
            column={2}
            title={row?.name}
            request={async () => ({
              data: row || {},
            })}
            params={{
              id: row?.name,
            }}
            columns={columns}
          />
        )}
      </Drawer>
      <Modal
        title={codeTableNumber}
        visible={detailModalVisible}
        onCancel={() => {
          setDetailModalVisible(false);
          setCodeTableNumber(undefined); // 重置标题
        }}
        style={{ width: 600, backgroundColor: 'white' }}
      >
        <StopwatchDetail dataSource={detailData} />
      </Modal>
    </PageContainer>
  );
};

export default Stopwatch;
